package org.wedding.center.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.date.DateUtil;
import org.wedding.dto.PageModel;
import org.wedding.center.dto.query.AttachQuery;
import org.wedding.center.entity.AttachInfo;
import org.wedding.center.entity.RightInfo;
import org.wedding.center.mapper.AttachInfoMapper;
import org.wedding.center.service.AttachInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.wedding.enums.system.ResultCodeEnum;
import org.wedding.utils.CommonResult;
import org.wedding.center.service.RightInfoService;
import org.wedding.center.util.*;
import org.springframework.stereotype.Service;
import org.wedding.utils.PageUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * 图片附件表(AttachInfo)表服务实现类
 *
 * @author songkaiyue
 * @since 2025-05-14 16:25:48
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AttachInfoServiceImpl extends ServiceImpl<AttachInfoMapper, AttachInfo> implements AttachInfoService {
    @Resource
    private QiniuUtils qiniuUtils;
    @Resource
    private ImageUtil imageUtil;
    @Resource
    private RightInfoService rightInfoService;

    /**
     * 分页查询所有数据
     *
     * @return
     */
    @Override
    public CommonResult<PageModel> findAll(AttachQuery query) {
        try {
            List<AttachInfo> list = baseMapper.selectAll(query);
            List<AttachInfo> setList = query.setList(PageUtil.getListPage(query.getCurrent(), query.getPageSize(), list), list.size());
            query.setList(setList, list.size());
            return CommonResult.success(query);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }

    }

    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult<AttachInfo> view(String id) {
        try {
            AttachInfo attachInfo = baseMapper.findById(id);
            return CommonResult.success(attachInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 新增数据
     *
     * @param attachInfo
     * @return
     */
    @Override
    public CommonResult add(AttachInfo attachInfo) {
        try {
//            if (StrUtil.isEmpty(attachInfo.getBusinessId())) return CommonResult.failed(ResultCodeEnum.PARAM_ERROR);
            attachInfo.setId(IdUtil.simpleUUID());
            attachInfo.setCreateTime(DateUtil.now());
            attachInfo.setDelFlag("0");
            baseMapper.insert(attachInfo);
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 修改数据
     *
     * @param attachInfo
     * @return
     */
    @Override
    public CommonResult updateEntity(AttachInfo attachInfo) {
        try {
            attachInfo.setUpdateTime(DateUtil.now());
            baseMapper.updateById(attachInfo);
            return CommonResult.success(attachInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 修改文件名
     *
     * @param id
     * @param fileName
     * @return
     */
    @Override
    public CommonResult updateFileName(String id, String fileName) {
        try {
            baseMapper.updateFileName(id, fileName);
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 删除数据
     *
     * @param ids
     * @return
     */
    @Override
    public CommonResult delete(List<String> ids) {
        try {
            if (ObjectUtil.isEmpty(ids)) return CommonResult.failed(ResultCodeEnum.PARAM_ERROR);
            for (String id : ids) {
                //删除七牛云图片
                AttachInfo attachInfo = baseMapper.findById(id);
                qiniuUtils.delete(attachInfo.getAttachName());
                //删除数据库数据
                baseMapper.upDeleteById(id);
            }
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    @Override
    @Transactional
    public CommonResult<AttachInfo> uploadAttach(AttachInfo attachInfo) {
        try {
            if (StrUtil.isEmpty(attachInfo.getFilePath())) {
                return CommonResult.failed(0, "文件不能为空！");
            }
            if (StrUtil.isEmpty(attachInfo.getFileName()) && StrUtil.isNotEmpty(attachInfo.getAttachName())) {
                attachInfo.setFileName(attachInfo.getAttachName());
            }
            //判断文件上传大小
            RightInfo rightInfo = rightInfoService.findOne().getData();
            if (ObjectUtil.isNotEmpty(rightInfo) && StrUtil.isNotEmpty(rightInfo.getFileSize())) {
                long size = attachInfo.getFileSize();
                //转化为M
                long maxSize = Long.parseLong(rightInfo.getFileSize()) * 1024 * 1024;
                if (size > maxSize) {
                    return CommonResult.failed(ResultCodeEnum.FILE_LIMIT_SIZE);
                }
            }
            String userId = StpUtil.getSession().get("userId").toString();
            if (StrUtil.isEmpty(userId)) {
                return CommonResult.failed(ResultCodeEnum.LOGIN_INF_EXPIRE);
            }
            attachInfo.setCreator(userId);
            if (StrUtil.isEmpty(attachInfo.getSort())) {
                attachInfo.setSort("5");
            }
            add(attachInfo);
            return CommonResult.success(attachInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 根据sort和businessId查询
     *
     * @param sort
     * @param businessId
     * @return
     */
    @Override
    public CommonResult<List<AttachInfo>> findBySortAndBusinessId(String sort, String businessId) {
        try {
            List<AttachInfo> list = baseMapper.findBySortAndBusinessId(sort, businessId);
            return CommonResult.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }
}
